//
//  ScanDeviceViewController.m
//  KEREN
//
//  Created by MW on 2023/3/15.
//

#import "ScanDeviceViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "BandDeviceVC.h"
#import "KRQuestionVC.h"
#import "DeviceLocationVC.h"
#import "KRBLEDeviceCell.h"
#import "BandDeviceVC.h"
@interface ScanDeviceViewController ()<AVCaptureMetadataOutputObjectsDelegate,TZImagePickerControllerDelegate,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, assign) int currentIndex;
@property (nonatomic, strong) UIImageView *sacnImageView;
@property (nonatomic, strong) UIButton *bleScanBtn;
@property (nonatomic, assign) BOOL isBleScan;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *bleBtn;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UILabel *tipsLbl;
@property (nonatomic, strong) UIView *btnBackView;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;
@property (nonatomic, assign) int timeout;//扫描超时时间
@property (nonatomic, strong) UIImageView *backImage;
@property (nonatomic, strong) UIButton *sdtIconBtn;
@property (nonatomic, strong) UILabel *sdtLbl;
@property (nonatomic, strong) CBPeripheral * _Nonnull peripheral;
@property (nonatomic, strong) NSMutableArray *dataArrM;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) NSMutableArray *advertisementDataArrM;//广播包数组
@end

@implementation ScanDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setViewLayout];
    _currentIndex = 0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeSDT) name:@"AVCaptureTorchModeOffSDT" object:nil];
    
    [self setNavViewWithRightTitle:@"常见问题" navColorIswhite:NO withTitle:@"绑定爱车"];
    WEAKSELF
    //TODO 国际化
    self.rightClickBlock = ^(void){
        if(weakSelf.backImage.hidden){
            TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:weakSelf];
            imagePC.allowPickingOriginalPhoto = YES;//原图
            imagePC.modalPresentationStyle = 0;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf presentViewController:imagePC animated:YES completion:nil];
            });
        }else{
            KRQuestionVC *vc = [[KRQuestionVC alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (void)setViewLayout{
    _backImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mainBack_image"]];
    _backImage.frame = CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT);
    _backImage.userInteractionEnabled = YES;
    [self.view addSubview:_backImage];
    
    _sacnImageView = [[UIImageView alloc] init];
    [self.view addSubview:_sacnImageView];
    [_sacnImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(56 + STATUSBAR_HEIGHT);
        make.width.height.offset(1080/2);
        make.centerX.equalTo(self.view);
    }];
    self.view.clipsToBounds = YES;
    _sacnImageView.clipsToBounds = YES;
    [self changsacnImage];
    
    _bleScanBtn = [UIButton setButtonWithTitle:@"开始扫描" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    [self.view addSubview:_bleScanBtn];
    [_bleScanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-BottomSpance_height);
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
    }];
    [_bleScanBtn addTarget:self action:@selector(bleScan) forControlEvents:UIControlEventTouchUpInside];
    
    
    _btnBackView = [[UIView alloc] init];
    [self.view addSubview:_btnBackView];
    [_btnBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(136);
        make.height.offset(40);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(_bleScanBtn.mas_top).offset(-24);
    }];
    _btnBackView.backgroundColor = rgba(1, 1, 1, 0.4);
    _btnBackView.layer.cornerRadius = 20;
    _btnBackView.clipsToBounds = YES;
    _bleBtn = [UIButton setButtonWithImage:@"ble_icon" cornerRadius:16 backColor:[UIColor clearColor]];
    [_btnBackView addSubview:_bleBtn];
    [_bleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(4);
        make.bottom.offset(-4);
        make.width.offset(64);
    }];
    _bleBtn.selected = YES;
    _bleBtn.backgroundColor = rgba(0, 0, 0, 0.4);
    
    _scanBtn = [UIButton setButtonWithImage:@"sacn_icon" cornerRadius:16 backColor:[UIColor clearColor]];
    [_btnBackView addSubview:_scanBtn];
    [_scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.offset(-4);
        make.top.offset(4);
        make.width.offset(64);
    }];
    [_bleBtn addTarget:self action:@selector(bleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_scanBtn addTarget:self action:@selector(scanBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _tipsLbl = [[UILabel alloc] init];
    [self.view addSubview:_tipsLbl];
    [_tipsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_bleBtn);
        make.bottom.equalTo(_btnBackView.mas_top).offset(-8);
    }];
    _tipsLbl.font = BFont(12);
    _tipsLbl.textColor = rgba(1, 1, 1, 0.6);
    //TODO 国际化
    _tipsLbl.text = @"蓝牙绑定";
    _sdtIconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sdtIconBtn setImage:[UIImage imageNamed:@"AVCaptureTorchModeOff"] forState:UIControlStateNormal];
    [_sdtIconBtn setImage:[UIImage imageNamed:@"AVCaptureTorchModeOn"] forState:UIControlStateSelected];
    [self.view addSubview:_sdtIconBtn];
    _sdtLbl = [UILabel setLblText:@"打开手电筒" font:BFont(14) withColor:Whire_Color inSubView:self.view];
    _sdtIconBtn.hidden = YES;
    _sdtLbl.hidden = YES;
    [_sdtIconBtn addTarget:self action:@selector(on_offSDT) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)becameActive {
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeSDT) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    if(self.backImage.hidden){
        self.sdtIconBtn.selected = NO;
        self.sdtLbl.text = @"打开手电筒";
    }
    if(self.backImage.hidden){
        [self stopRunning];
        [self timer];
        [self setAVCaptureDevice];
    }
}

- (void)closeSDT{
    self.sdtIconBtn.selected = NO;
    self.sdtLbl.text = @"打开手电筒";
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _sdtIconBtn.selected = NO;
    [self invalidateTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)bleBtnClick{
    self.backImage.hidden = NO;
    _sdtIconBtn.hidden = YES;
    _sdtLbl.hidden = YES;
    self.sdtLbl.text = @"打开手电筒";
    [self invalidateTimer];
    
    [self changsacnImage];
    [self stopRunning];
    _scanBtn.backgroundColor = [UIColor clearColor];
    _bleBtn.backgroundColor = rgba(0, 0, 0, 0.4);
    _bleScanBtn.hidden = NO;
    _tipsLbl.text = @"蓝牙绑定";
    self.rightLbl.text = @"常见问题";
    self.titleLbl.text = @"绑定爱车";
    [_bleScanBtn setTitle:@"开始扫描" forState:UIControlStateNormal];
    [_tipsLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_bleBtn);
        make.bottom.equalTo(_btnBackView.mas_top).offset(-8);
    }];
    [_sacnImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(56 + STATUSBAR_HEIGHT);
        make.width.height.offset(1080/2);
        make.centerX.equalTo(self.view);
    }];
    
}

-(void)scanBtnClick{
    self.backImage.hidden = YES;
    [self changsacnImage];
    [self invalidateTimer];
    [self timer];
    self.titleLbl.text = @"扫码绑定";
    self.rightLbl.text = @"相册导入";
    _scanBtn.backgroundColor = rgba(0, 0, 0, 0.4);
    _bleBtn.backgroundColor = [UIColor clearColor];
    _bleScanBtn.hidden = YES;
    _tipsLbl.text = @"扫码绑定";
    [_tipsLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_scanBtn);
        make.bottom.equalTo(_btnBackView.mas_top).offset(-8);
    }];
    [_sacnImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        if(DEVICE_HEIGHT < 750){
            make.top.offset(100 + STATUSBAR_HEIGHT);
        }else{
            make.top.offset(140 + STATUSBAR_HEIGHT);
        }
        make.width.height.offset(260);
        make.centerX.equalTo(self.view);
    }];
    _sdtIconBtn.selected = NO;
    [_sdtIconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_sacnImageView.mas_bottom).offset(22);
        make.width.height.offset(58);
        make.centerX.equalTo(self.view);
    }];
    _sdtIconBtn.hidden = NO;
    _sdtLbl.hidden = NO;
    [_sdtLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_sdtIconBtn.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
    [self setAVCaptureDevice];
}

- (void)setAVCaptureDevice{
    //判断权限
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
#if TARGET_IPHONE_SIMULATOR  //模拟器
                NSString *title = @"使用相机功能，请使用真机";
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                alertView.delegate = self;
                [alertView show];
#else //if TARGET_OS_IPHONE      //真机
                [self loadScanView];
                [self startRunning];
#endif
            } else {
                NSString *title = @"请前往开启相机权限：手机设置->隐私->相机->（可人APP打开）";
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                alertView.delegate = self;
                [alertView show];
            }
            
        });
    }];
    
}

- (void)on_offSDT{
    _sdtIconBtn.selected = !_sdtIconBtn.selected;
    if(_sdtIconBtn.selected){
        _sdtLbl.text = @"关闭手电筒";
    }else{
        _sdtLbl.text = @"打开手电筒";
    }
    [self FlashlightON];
}

-(void)FlashlightON{
    AVCaptureDevice *device =[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //修改前必须先锁定
    [device lockForConfiguration:nil];
    //必须判定是否有闪光灯，否则如果没有闪光灯会崩溃
    if([device hasFlash]) {
        if(device.torchMode==AVCaptureFlashModeOff) {
            device.torchMode=AVCaptureTorchModeOn;
        }else if(device.torchMode==AVCaptureFlashModeOn) {
            device.torchMode=AVCaptureTorchModeOff;
        }
    }
    [device unlockForConfiguration];
}

- (void)bleScan{
    self.isBleScan = YES;
    _timeout = 0;
    [self invalidateTimer];
    [self timer];
    [self.dataArrM removeAllObjects];
    [self.advertisementDataArrM removeAllObjects];
    WEAKSELF
    [_bleScanBtn setTitle:@"扫描中..." forState:UIControlStateNormal];
    [[HABleManager sharedManager] scanPeriperals:^(CBCentralManager * _Nonnull central, CBPeripheral * _Nonnull peripheral, NSDictionary<NSString *,id> * _Nonnull advertisementData, NSNumber * _Nonnull RSSI) {
        if(advertisementData[@"kCBAdvDataServiceUUIDs"] && [advertisementData[@"kCBAdvDataServiceUUIDs"] isKindOfClass:[NSArray class]]){
            NSArray *arr = [peripheral.advertisementData objectForKey:@"kCBAdvDataServiceUUIDs"];
            NSString *sn = [self CBUUIDToString:arr[0]];
            sn = [self getASCIIString:sn];
            if([sn containsString:@"KRen"]){
                if(![weakSelf.dataArrM containsObject:peripheral]){
                    [weakSelf.dataArrM addObject:peripheral];
                    [weakSelf.advertisementDataArrM addObject:advertisementData];
                }
                [UIView animateWithDuration:0.5 animations:^{
                    weakSelf.bottomView.frame = CGRectMake(0, DEVICE_HEIGHT - 390, DEVICE_WIDTH, 390);
                }];
                [weakSelf.tableView reloadData];
            }
        }
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if([HABleManager sharedManager].centralManager.state == CBManagerStatePoweredOff){
            weakSelf.isBleScan = NO;
            [weakSelf invalidateTimer];
            [[KRAlartManager shareInstance] showBLENotOpenAlert];
            return;
        }
    });
}

- (void)closeTab{
    [UIView animateWithDuration:0.5 animations:^{
        self.bottomView.frame = CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, 390);
    }];
}

- (void)connectToPeripheral:(UIButton *)sender{
    CBPeripheral * _Nonnull peripheral = self.dataArrM[sender.tag];
    NSDictionary *dict = self.advertisementDataArrM[sender.tag];
    
    NSArray *arr = [dict objectForKey:@"kCBAdvDataServiceUUIDs"];
    NSString *sn = [self CBUUIDToString:arr[0]];
    sn = [self getASCIIString:sn];
    sn = [sn substringFromIndex:4];
    
    NSString *sn_code = [NSString stringWithFormat:@"%@%@",sn,[peripheral.name substringWithRange:NSMakeRange(peripheral.name.length - 4, 4)]];
    [[KRAlartManager shareInstance] showLodingAlertView:@""];
    [NetworkingTool POST:device_check_bluetooth parameters:@{@"sn":sn_code} isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            BandDeviceVC *vc = [[BandDeviceVC alloc] init];
            vc.snCode = sn_code;
            vc.isFromBLEVC = YES;
            vc.peripheral = peripheral;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
    }];
}

- (void)invalidateTimer{
    [[HABleManager sharedManager] stopScanPeriperals];
    _currentIndex = 0;
    if(_timer){
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)loadScanView {
    //获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    self.session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [self.session addInput:input];
    [self.session addOutput:output];
    self.scanType = WQCodeScannerTypeAll;
    //设置扫码支持的编码格式
    switch (self.scanType) {
        case WQCodeScannerTypeAll:
            output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,
                                         AVMetadataObjectTypeEAN13Code,
                                         AVMetadataObjectTypeEAN8Code,
                                         AVMetadataObjectTypeUPCECode,
                                         AVMetadataObjectTypeCode39Code,
                                         AVMetadataObjectTypeCode39Mod43Code,
                                         AVMetadataObjectTypeCode93Code,
                                         AVMetadataObjectTypeCode128Code,
                                         AVMetadataObjectTypePDF417Code];
            break;
            
        case WQCodeScannerTypeQRCode:
            output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode];
            break;
            
        case WQCodeScannerTypeBarcode:
            output.metadataObjectTypes=@[AVMetadataObjectTypeEAN13Code,
                                         AVMetadataObjectTypeEAN8Code,
                                         AVMetadataObjectTypeUPCECode,
                                         AVMetadataObjectTypeCode39Code,
                                         AVMetadataObjectTypeCode39Mod43Code,
                                         AVMetadataObjectTypeCode93Code,
                                         AVMetadataObjectTypeCode128Code,
                                         AVMetadataObjectTypePDF417Code];
            break;
            
        default:
            break;
    }
    
    _layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:_layer atIndex:0];
}

- (void)startRunning {
    
    if (self.session) {
        [self.session commitConfiguration];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.session startRunning];
        });
    }
}
- (void)stopRunning {
    [_layer removeFromSuperlayer];
    if(self.session){
        [self.session stopRunning];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArrM.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KRBLEDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRBLEDeviceCell"];
    CBPeripheral * _Nonnull peripheral = self.dataArrM[indexPath.row];
    cell.nameLbl.text = peripheral.name;
    cell.matchBtn.tag = indexPath.row;
    CBUUID* serviceId = [CBUUID UUIDWithString:KRServiceUUID];
    NSArray<CBPeripheral*>* peripheralArray = [[HABleManager sharedManager].centralManager retrieveConnectedPeripheralsWithServices:@[serviceId]];
    [cell.matchBtn setTitle:@"立即配对" forState:UIControlStateNormal];
    [cell.matchBtn addTarget:self action:@selector(connectToPeripheral:) forControlEvents:UIControlEventTouchUpInside];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}


#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    [self.session stopRunning];
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects[0];
        NSString *result = metadataObject.stringValue;
        [self analysisCode:result];
    }
}

- (void)analysisCode:(NSString *)result{
    if([result containsString:@"KEREN-EBIKE"]){
        result = [result stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSArray *temp;
        if([result containsString:@"："]){
            temp = [result componentsSeparatedByString:@"："];
        }
        if([result containsString:@":"]){
            temp = [result componentsSeparatedByString:@":"];
        }
        
        if(temp.count > 1){
            BandDeviceVC *vc = [[BandDeviceVC alloc] init];
            vc.snCode = temp[1];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        [[KRAlartManager shareInstance] showErrorAlert:@"该二维码无效，请扫描正确的二维码"];
        [self startRunning];
    }
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    
    UIImage *pickImage = photos.firstObject;
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];
    // 获取选择图片中识别结果
    NSArray *features = [detector featuresInImage:[CIImage imageWithData:UIImagePNGRepresentation(pickImage)]];
    if (features.count >= 1) {
        // 取第一个元素就是二维码所存放的文本信息
        CIQRCodeFeature *feature = features[0];
        NSString *scannedResult = feature.messageString; // 触发回调
        [self analysisCode:scannedResult];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSString*)CBUUIDToString:(CBUUID*)cbuuid;
{
    NSData* data = cbuuid.data;
    if ([data length] == 2)
    {
        const unsigned char *tokenBytes = [data bytes];
        return [NSString stringWithFormat:@"%02x%02x", tokenBytes[0], tokenBytes[1]];
    }
    else
    {
        NSUUID* nsuuid = [[NSUUID alloc] initWithUUIDBytes:[data bytes]];
        return [nsuuid UUIDString];
    }
    return [cbuuid description]; // an error?
}


- (void)changsacnImage{
    if(!self.backImage.hidden){
        _sacnImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"scan_000%02d",_currentIndex]];
        _currentIndex ++;
        if(_currentIndex == 59){
            _currentIndex = 0;
            _timeout +=2;
        }
        if(_timeout > 15){
            //扫描15秒
            [self invalidateTimer];
            _bleScanBtn.enabled = YES;
            [_bleScanBtn setTitle:@"重新扫描" forState:UIControlStateNormal];
            if(_dataArrM.count == 0){
                [[KRAlartManager shareInstance] showBLENotFoundDeviceAlert];
            }
        }
        
    }else{
        _currentIndex ++;
        _sacnImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"scan_code_000%02d",_currentIndex]];
        if(_currentIndex == 39){
            _currentIndex = 0;
        }
    }
}

-(NSTimer *)timer{
    if(!_timer){
        _currentIndex = 0;
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.033 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [self changsacnImage];
        }];
    }
    return _timer;
}

- (NSMutableArray *)dataArrM{
    if(!_dataArrM){
        _dataArrM = [NSMutableArray array];
    }
    return _dataArrM;
}

- (NSMutableArray *)advertisementDataArrM{
    if(!_advertisementDataArrM){
        _advertisementDataArrM = [NSMutableArray array];
    }
    return _advertisementDataArrM;
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 60, DEVICE_WIDTH, 300)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 100;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRBLEDeviceCell" bundle:nil] forCellReuseIdentifier:@"KRBLEDeviceCell"];
        // _tableView
        [self.bottomView addSubview:_tableView];
        
    }
    return _tableView;
}

- (UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, DEVICE_HEIGHT, DEVICE_WIDTH, 390)];
        _bottomView.backgroundColor = Whire_Color;
        UILabel *titleLbl = [UILabel setLblText:@"设备列表" font:BFont(20) withColor:Black_Color inSubView:_bottomView];
        [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(15);
            make.left.offset(24);
        }];
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:closeBtn];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.offset(44);
            make.right.offset(6);
            make.centerY.equalTo(titleLbl);
        }];
        [closeBtn setImage:[UIImage imageNamed:@"NavBar_Default_Close"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(closeTab) forControlEvents:UIControlEventTouchUpInside];
        [UIView setLineViewWithframe:CGRectMake(0, 58, DEVICE_WIDTH, 1) forinView:_bottomView];
        [self.view addSubview:_bottomView];
    }
    return _bottomView;
}

-(NSString*)getASCIIString:(NSString*)strHex
{
    strHex =[strHex stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSMutableString *strAscii = [NSMutableString string];
    for (int i=0;i<strHex.length; i+=2) {
        NSString *charValue = [strHex substringWithRange:NSMakeRange(strHex.length - 2 - i,2)];
        unsigned int _byte;
        [[NSScanner scannerWithString:charValue] scanHexInt: &_byte];
        if (_byte >= 32 && _byte < 127) {
            [strAscii appendFormat:@"%c", _byte];
        } else {
            [strAscii appendFormat:@"[%d]", _byte];
        }
    }
    DDLogInfo(@"Hex: %@", strHex);
    DDLogInfo(@"Ascii: %@", strAscii);
    return strAscii;
}

@end
